<template>
	<view>
		<uni-card>
			<text>排行榜</text>
			<uni-segmented-control 
			:current="current" 
			:values="items" 
			@clickItem="onClickItem" />
								
								<uni-list>
									<uni-list-item 
										v-for="(item,index) in books"
										:key = index
										:title="item.title"
										:note="item.author"
										:to="`../bookinfo/bookinfo?id=${item.id}`"
									></uni-list-item>
								
								</uni-list>
		</uni-card>
		
		<uni-card>
			<text>完本推荐</text>
		
								
								<uni-list>
									<uni-list-item 
										v-for="(item,index) in books"
										:key = index
										:title="item.title"
										:note="item.author"
										:to="`../bookinfo/bookinfo?id=${item.id}`"
									></uni-list-item>
								
								</uni-list>
		</uni-card>
	</view>
</template>

<script>
	import {fetchHot, fetchTop, fetchLatest} from '../../api/api.js'
	export default {
		data() {
			return {
				menus: [
					{
						key: "top",
						value: '推荐榜'
					}, 
					{
						key: "hot",
						value: '人气榜'
					}, 
					{
						key: "latest",
						value: '新书榜'
					}
				],
				current: 0,
				booksStore: {}
			};
		},
		onLoad(option) {
			this.retrive();
		},
		methods: {
			retrive() {
				console.log(this.current)
				if(this.booksStore[this.current] == null) {
					const type = this.menus[this.current].key;
					let fn;
					
					if(type == "hot") {
						fn = () => fetchHot();
					}
					else if(type == "top") {
						fn = () => fetchTop();
					}
					else if(type == "latest") {
						fn = () => fetchLatest();
					}
					
					fn().then(res => {
						
						this.booksStore[this.current] = res.data.data;
						
						console.log(this.booksStore)
					})
				}
			},
			onClickItem(e) {
				this.current = e.currentIndex;
				this.retrive()
			}
		},
		computed: {
			items() {
				return this.menus.map(t=>t.value);
			},
			books() {
				if(this.booksStore && this.booksStore[this.current]) {
					return this.booksStore[this.current];
				}
				
				return null;
			}
		}
	}
</script>

<style lang="scss">

</style>
